package com.googlecode.struts2scope;

import java.util.Set;

import com.googlecode.struts2scope.context.Context;
import com.googlecode.struts2scope.scope.annotation.scanner.FieldMetadata;
import com.googlecode.struts2scope.scope.annotation.scanner.ScopeAnnotationScanner;
import com.googlecode.struts2scope.util.BeanProvider;
import com.opensymphony.xwork2.ActionInvocation;

public class GenericContextExecutionFlow implements ContextExecutionFlow {

	private Object actionObject;
	private Set<FieldMetadata> fields;

	@SuppressWarnings("unchecked")
	public void init(ActionInvocation invocation) {		
		actionObject = invocation.getAction();

		ScopeAnnotationScanner scopeAnnotationScanner = new ScopeAnnotationScanner();
		fields = scopeAnnotationScanner.scanClass(actionObject.getClass());

	}

	public void after() {
		for (FieldMetadata fieldMetadata : fields) {
			Object value = BeanProvider.getProperty(actionObject, fieldMetadata.getName());
			if (value != null) {
				Context context = fieldMetadata.getScopeType().getFactory().buildContext();
				context.setAttribute(fieldMetadata.getKey(), value);
			}
		}
	}

	public void before() {
		for (FieldMetadata fieldMetadata : fields) {

			Context context = fieldMetadata.getScopeType().getFactory().buildContext();
			Object value = context.getAttribute(fieldMetadata.getKey());
			if (value != null) {
				BeanProvider.setProperty(actionObject, fieldMetadata.getName(), value);
			}
		}

	}
}
